#include "BlueMonkey.h"
#include "Circus.h"

BlueMonkey::BlueMonkey(): 
Monkey(), 
ySpeed(0.0f), 
isJumping(false), 
game(0), 
jumpSprite(0)
{
	isBlueMonkey = true;
}

BlueMonkey::BlueMonkey(int x, int y, Circus *circus): 
Monkey(), 
isJumping(false), 
ySpeed(0.0f), 
game(circus), 
jumpSprite(0) {
	speed = BM_SPEED;

	// drawing info
	SDL_Rect dstBlueMonkey;
	dstBlueMonkey.x = x;
	dstBlueMonkey.y = y;
	dstBlueMonkey.w = BM_WIDTH;
	dstBlueMonkey.h = BM_HEIGHT;

	// set the animation properly
	SetTexture(BM_PATH);
	SetAnimation(BM_SRC_X, BM_SRC_Y, BM_SRC_W, BM_SRC_H, BM_SRC_OFFSET, BM_FRAMES, BM_ANIM_FPS, BM_ANIM_LOOP, BM_ANIM_HORZ);
	SetDstRect(dstBlueMonkey);

	// collider
	delete collider;
	collider = new CustomRectangle((float)x, (float)y, (float)(BM_WIDTH - BM_COLLIDER_OFFSET), (float)(BM_HEIGHT - BM_COLLIDER_OFFSET));
	isCircular = false;

	// jump sprite
	SDL_Rect srcBlueMonkeyJump;
	srcBlueMonkeyJump.x = BMJ_SRC_X;
	srcBlueMonkeyJump.y = BMJ_SRC_Y;
	srcBlueMonkeyJump.h = BMJ_SRC_H;
	srcBlueMonkeyJump.w = BMJ_SRC_W;
	jumpSprite = new Sprite(BM_PATH);
	jumpSprite->SetSrcRect(srcBlueMonkeyJump);
	jumpSprite->SetDstRect(dstRect);
	jumpSprite->SetVisible(false);
}

void BlueMonkey::Update(float dt) {
	Monkey::Update(dt);

	if (!isJumping) {
		// jump if appropriate
		JumpCheck();
	} else {
		// apply gravity if in thew air
		ySpeed += GRAVITY * dt;
	}

	// apply the jump movement
	SetPosition(dstRect.x, dstRect.y + (int)(ySpeed * dt));

	// check if touching the ground and reposition if below ground
	if (dstRect.y >= GROUND_HEIGHT - BM_HEIGHT) {
		isJumping = false;
		SetPosition(dstRect.x, GROUND_HEIGHT - BM_HEIGHT);
	}
	
	// display or hide
	if (dstRect.x < 0 - dstRect.w) {
		// make invisible if past the screen
		isVisible = false;
		jumpSprite->SetVisible(false);
	} else {
		// display the right animation
		if (isJumping) {
			jumpSprite->SetPosition(dstRect.x, dstRect.y);
			jumpSprite->SetVisible(true);
			isVisible = false;
		} else {
			isVisible = true;
			jumpSprite->SetVisible(false);
		}
	}
}

void BlueMonkey::JumpCheck() {
	for (int i = 0; i < game->GetMonkeys()->GetLength(); i++) {
		// check all monkeys
		if ((*game->GetMonkeys())[i] != this) {
			// except itself, and get the horizontal distance between the two
			int dif = dstRect.x - ((*game->GetMonkeys())[i]->GetRect().x + (*game->GetMonkeys())[i]->GetRect().w);
			if (dif >= 0 && dif <= JUMP_DIF) {
				// remove the effects of gravity and make it jump
				ySpeed = (float)JUMP_SPEED;
				isJumping = true;
				break;
			}
		}
	}
}

BlueMonkey::~BlueMonkey() {

}